const express = require('express')
const router = express.Router()
const { LOGGED } = require('../logged')
const mysql = require('mysql')

const db_vx = mysql.createConnection({
    host: '127.0.0.1',
    user: 'root',
    password: '020522',
    database: 'vx'
})
// 刷新数据库防断连
setInterval(function () {
    db_vx.query('SELECT 1');
}, 1080000);

// 鉴权中间件
function requireAuth(req, res, next) {
    console.log(req.session);
    if (req.session.user !== undefined) {
        return next(); // 如果用户已经通过身份验证，则继续执行下一个中间件
    } else {
        res.send({
            code: 401,
            msg: "未登录"
        }) // 如果用户未经授权，则返回401错误
    }
}
// 注册
router.post('/vx/api/signup', (req, res) => {
    let { username, password, key, name } = req.body;
    console.log(req.query);
    console.log(req.body);
    if (!(username && password)) {
        return res.send({
            code: 400,
            msg: username ? "缺少密码" : "缺少用户名"
        })
    }
    if (key.toUpperCase() != 'MMDCCJ') {
        return res.send({
            code: 400,
            msg: "错误的管理员KEY,请联系管理员获取"
        })
    }
    if (!name) {
        return res.send({
            code: 400,
            msg: "缺少姓名"
        })
    }
    const checkSQL = "SELECT adminName FROM admin WHERE adminName = ?"
    db_vx.query(checkSQL, [username], (err, result) => {
        if (err) return res.send({
            code: 400,
            msg: "查询错误",
            data: err
        })
        if (result.length != 0) {
            return res.send({
                code: 400,
                msg: '该用户名已被注册',
                data: null
            })
        }
        const signUpSQL = "INSERT INTO admin(adminName,adminPassword,name) value(?,?,?)"
        db_vx.query(signUpSQL, [username, password, name], (err, result) => {
            if (err) return res.send({
                code: 400,
                msg: "新增错误",
                data: err
            })
            // 影响的行数不等于1则插入失败
            if (result.affectedRows != 1) {
                return res.send({
                    code: 400,
                    msg: "新增管理员失败"
                })
            }
            req.session.status = { username, password }
            return res.send({ code: 200, msg: '注册成功' })
        })
    })
})
// 后台登录
router.post('/vx/api/login', (req, res) => {
    const { username, password } = req.body;
    const user = { username, password };
    if (!(username && password)) {
        return res.send({ code: 400, msg: username ? '缺少密码' : '缺少用户名' })
    }
    const loginSQL = 'SELECT adminPassword FROM admin WHERE adminName=?';
    db_vx.query(loginSQL, [username], (err, result) => {
        if (err) return res.send({
            code: 400,
            msg: err
        })
        if (result.length == 0 || result == undefined) {
            return res.send({ code: 400, msg: '登录失败,不存在的用户名' })
        }
        if (result[0].adminPassword == password) {
            req.session.user = user;
            req.session.save();
            return res.send({ code: 200, msg: '登录成功', userName: username })
        } else {
            return res.send({ code: 400, msg: '密码错误' })
        }
    })
})
router.post('/vx/api/isLogin', requireAuth, (req, res) => {
    return res.send({ code: 200, msg: 'success' })
})
// 管理员工管理
router.get('/vx/api/getadmin', LOGGED, (req, res) => {
    const selectSQL = "SELECT id,adminName,adminPassword,name,adminType FROM admin"
    db_vx.query(selectSQL, (err, result) => {
        if (err) return res.send({
            code: 400,
            msg: err
        })
        return res.send({
            code: 200,
            msg: '成功',
            data: result
        })
    })

})
// 获取用户信息，需要鉴权 暂时未加入鉴权
router.get('/vx/api/b/getUserInfo', (req, res) => {
    const selectSQL = `
        SELECT id,openid,name,age,gender,vaccine_times FROM user_info
    `
    db_vx.query(selectSQL, (err, result) => {
        if (err) return res.send({
            code: 400,
            msg: err
        })
        return res.send({
            code: 200,
            msg: '成功',
            data: result
        })
    })
})
// 获取疫苗信息，需要鉴权 暂时未加入鉴权
router.get('/vx/api/b/getVaccineInfo', (req, res) => {
    const openid = req.query.openid
    const selectSQL = `
        SELECT id,injection_date,injection_location,vaccine_name FROM vaccine
        WHERE openid = ?
    `
    db_vx.query(selectSQL, [openid], (err, result) => {
        if (err) return res.send({
            code: 400,
            msg: err
        })
        if (result?.length == 0 || result.length === undefined) {
            return res.send({
                code: 201,
                msg: '未查询到该用户的疫苗注射情况'
            })
        }
        return res.send({ code: 200, data: result, msg: 'success' })

    })
})
// 更新核酸信息API
router.post('/vx/api/updatePCR', LOGGED, (req, res) => {
    const openid = req.query.openid;
    if (!openid) {
        return res.send({
            code: 200,
            msg: "openid为空"
        })
    }
    const code = req.query.code;
    /*
        该API的状态码说明：
            1:插入
            2:更新
            3:删除 
    */
    switch (code) {
        case "1":
            const insertSQL = "INSERT INTO pcr_test SET ?";
            const effective_time = req.query.effective_time;
            const pcr_test_loc = req.query.pcr_test_loc;
            const Checked = req.query.Checked;
            const test_date = req.query.test_date
            const params = {
                openid,
                effective_time,
                pcr_test_loc,
                Checked,
                test_date
            }
            // 检查是否缺少参数
            if (!effective_time && pcr_test_loc && Checked && test_date) {
                return res.send({
                    code: 200,
                    msg: "缺少参数",
                    errParams: params
                })
            }
            db_vx.query(insertSQL, params, (err, result) => {
                if (err) return res.send({
                    code: 400,
                    msg: "错误",
                    data: err
                })
                if (result.affectedRows != 1) {
                    return res.send({
                        code: 400,
                        msg: "插入失败",
                    })
                }
                return res.send({
                    code: 200,
                    msg: "插入核酸数据成功"
                })
            })
            return
        case "2":
            return
        case "3":
            return
        default:
            return res.send({
                code: 400,
                msg: "错误的编码",
                errCode: code
            })
    }
})

module.exports = router